$(function() {
	ip = location.host;
	//获取LKJ选择的软件组合
	changeObjs = JSON.parse(window.localStorage.getItem('changeObjs'));
	//选择平台
	lkjPlatFormId = window.localStorage.getItem('lkjPlatFormId');
	versionChangeWebSocket = null;
	contentAllData=null;//所有软件的数据对象
	currentAllData = null;//选择的软件数据对象
	//获取LKJ软件版本下都有哪些类型的软件
	getVersionTypesName('1');
	$('#btns').css('margin-top',$(window).height() - 128);
	$('.module').css('height',$(window).height() - 148);
});

//获取LKJ软件版本下都有哪些类型的软件
function getVersionTypesName(sId){
	$.ajax({
		url : "../../../LKJSoftwareVersion/getTypeName",
		type : "post",
		data : {
			"sId" : sId,
			"type" : ""
		},
		dataType : "json",
		async:false,
		success : function(data) {
			if(data.flag==0){
				contentAllData = data.content;
				editAllData();
			}else{
				contentAllData="";
			}
		},
		error : function() {
		}
	});
}

//根据选择的软件，编辑数据
function editAllData(){
	//重置获取的软件数据的顺序，为了排版美观
	//把揭示数据添加到主机单元中
	contentAllData.splice(17,0,contentAllData[23]);
	//删除多余的揭示数据
	contentAllData.splice(24,1);
	//功能扩展和主控位置替换
	contentAllData.splice(18, 1,contentAllData.splice(21, 1, contentAllData[18])[0]);
	currentAllData = [];
	var contentAllDataCopy = [].concat(JSON.parse(JSON.stringify(contentAllData)));
	//筛选被选择的软件
	for(var i = 0;i<contentAllDataCopy.length;i++){
		for(var j = 0;j<changeObjs.length;j++){
			if(contentAllDataCopy[i].TYPE == changeObjs[j].id.split('_')[0]){
				var postionArray = changeObjs[j].position.split('');
				for(var k = 0;k<postionArray.length;k++){
					if(Number(postionArray[k]) == 1){
						var obj = new Object();
						obj.DISPLAY_ORDER=contentAllDataCopy[i].DISPLAY_ORDER;
						obj.SYS_NAME=contentAllDataCopy[i].SYS_NAME;
						obj.TYPE=contentAllDataCopy[i].TYPE;
						obj.VERSIONNAME=getVersionById(contentAllDataCopy[i].TYPE,changeObjs[j].fileId);
						obj.XIBIE=getVersionNameById(contentAllDataCopy[i].TYPE,k);
						obj.INDEX = k;
						obj.ID = changeObjs[j].id;
						obj.SPANVALUE = changeObjs[j].spanValue;
						currentAllData.push(obj);
					}
				}
			}
		}
	}
	
	//DIM放到最后，DIM放到最最后
	setDIM();
	getVersionTypes();
}
//DIM放到最后，DIM放到最最后
function setDIM(){
	var endDIM = -1;
	for(var i = 0;i<currentAllData.length;i++){
		if(currentAllData[i].SPANVALUE =="DMI软件"
			||currentAllData[i].SPANVALUE =="读卡软件"
				||currentAllData[i].SPANVALUE =="按键软件"
					||currentAllData[i].SPANVALUE =="资源文件"
						||currentAllData[i].SPANVALUE =="字库"
							||currentAllData[i].SPANVALUE =="语音"){
			endDIM++;
		}else{
			break;
		}
	}
	
	var newDIMDataArray = currentAllData.slice(0,endDIM+1);
	currentAllData = currentAllData.slice(endDIM+1);
	
	var endDIMCell = -1;
	for(var i = 0;i<newDIMDataArray.length;i++){
		if(newDIMDataArray[i].SYS_NAME == "DMI软件"){
			endDIMCell++;
		}else{
			break;
		}
	}
	
	var newDIMDataArray1 = newDIMDataArray.slice(0,endDIMCell+1);
	var newDIMDataArray2 = newDIMDataArray.slice(endDIMCell+1);
	
	var lastDIMArray = newDIMDataArray2.concat(newDIMDataArray1);
	
	currentAllData = currentAllData.concat(lastDIMArray);
	console.log();
}

//根据版本类型和软件类型查询下拉文件内容
function getVersionById(type,fileId){
	var softName = '';//软件名称
	$.ajax({
		url : "../../../LKJSoftwareVersion/getVersionName",
		type : "post",
		data : {
			"sId" : '1',
			"type" : type
		},
		dataType : "json",
		async:false,
		success : function(data) {
			if(data.flag==0){
				for(var i = 0;i<data.content.length;i++){
					if(fileId == data.content[i].VERSION_ID){
						softName = data.content[i].VERSION_NAME+"_"+data.content[i].VERSION_NUMBER+"("+data.content[i].VERSION_DETAIL+")";
					}
				}
				
				
			}
		},
		error : function() {
		}
	});
	return softName;
}

//根据版本类型和软件类型查询下拉文件内容
function getVersionNameById(type,index){
	var valueStr='';//软件
	var str1 = "1,3,4,5,6";
	var str2 = "7,8,9,10,11,12,13";
	if(str1.indexOf(type)>=0){
		if(index == 0){
			valueStr = 'I 端 A机';
		}else if(index == 1){
			valueStr = 'I 端 B机';
		}else if(index == 2){
			valueStr = 'II端 A机';
		}else{
			valueStr = 'II端 B机';
		}
	}else if(type==2){
		if(index == 0){
			valueStr = 'I 端';
		}else{
			valueStr = 'II端';
		}
	}else if(str2.indexOf(type)>=0){
		if(index == 0){
			valueStr = 'I 系 A模';
		}else if(index == 1){
			valueStr = 'I 系 B模';
		}else if(index == 2){
			valueStr = 'II系 A模';
		}else{
			valueStr = 'II系 B模';
		}
	}else if(type==14){
		if(index == 0){
			valueStr = 'I 系';
		}else{
			valueStr = 'II系';
		}
	}else if(type==16){
		var listArray = ['电源 I 系','电源 II系','数字 I 系','数字 II系','模拟 I 系','模拟 II系','通信 I 系','通信 II系','主控 I 系','主控 II系','检测 I 系','检测 II系','冷却 I 系','冷却 II系','制动','隔离'];
		valueStr = listArray[index];
	}else if(type==15||type==17||type==19||type==21){
		if(index == 0){
			valueStr = 'A机';
		}else{
			valueStr = 'B机';
		}
	}else{
		valueStr = '所在位置';
	}
	return valueStr;
}

//初始化右侧版本换装内容
function getVersionTypes(){
	$("#content").empty();
	str ="";
	str+='<div class="module">';
	str+=getSelectValue(currentAllData);
	$("#content").append(str);
    $("#changeBtn").prop("disabled", false);
}
//将查询到的软件类型进行组装展示各个标签
function getSelectValue(content){
	var str="";
	if(content!=""&&content!=null){
		for(var i=0;i<content.length;i++){
			str+='<div id='+content[i].TYPE+"_"+content[i].INDEX+'><span class="spans">';
			str+=content[i].SYS_NAME;
			str+='</span><div class="signSelect" disabled="true">'+content[i].VERSIONNAME+'</div>';
			str+='<div class="signSelect" disabled="true" style="width:138px;">'+content[i].XIBIE+'</div>';
			str+="<div class='statusmsg'>进度</div><div class='progress progress-striped'><div id='progress_"+content[i].TYPE+"_"+content[i].INDEX+"' class='progress-bar progress-bar-success' role='progressbar' style='width:0%;'>0%</div></div>";
			str+="<div class='statusmsg'>状态</div><div class='progressStatus'>未开始</div></div>";
		}
	}
	return str;
}
//将查询到的下拉内容组合放到对应的位置
function ajaxOption(content){
	var str="<option value=''></option>";
	if(content!=""&&content!=null){
		for(var i=0;i<content.length;i++){
			str+="<option value="+content[i].VERSION_ID+">"+content[i].VERSION_NAME+"</option>";
		};
	}
	return str;
}


//换装请求成功后，创建websocket连接，获取换装进度
function initWC(data){
	if(window.WebSocket){
		//初始化websocket链接，并发送数据，如果链接成功则将下拉框以及按钮置为不可用状态
		versionChangeWebSocket = new WebSocket('ws://'+ip+'/asts/versionChange');
		
		versionChangeWebSocket.onmessage = function(event) {
			getAllDataWebSocketMessage(event);
		};
		
		versionChangeWebSocket.onerror = function(event) {
			  console.log('websocket链接异常');
			  versionChangeWebSocket.close();
		};
		versionChangeWebSocket.onopen = function(event) {
			//websocket打开后发送信息
			versionChangeWebSocket.send(data);
			changeDisable(true);
		};
		versionChangeWebSocket.onclose = function(event){
			changeDisable(false);
			console.log(event.reason);//输出关闭原因
			
		};
    }else{
        console.log('This browser does not supports WebSocket');
    }
}
function getAllDataWebSocketMessage(event){
	var data = JSON.parse(event.data);//获取到后台推送过来的数据
	showDataStatus(data);
};

//根据websocket返回的结果刷新显示进度条和文字
function showDataStatus(data){
	for(var i = 0;i<currentAllData.length;i++){
		//根据TYPE解析接收到的数据是哪个软件的进度
		if(currentAllData[i].TYPE == data.id.split('_')[0]){
			for(var j = 0;j<data.result.length;j++){
				//如果result!=-1，说明有进度，那么刷新对应进度条
				if(data.result[j].result!='-1'){
					updateProgress(data.result[j].result,currentAllData[i].TYPE+"_"+j,data.result[j].progress);
				}
			}
			break;
		}
	}
}

//刷新对应进度条显示
function updateProgress(result,id,progressData){
	var progress = 0;//进度条进度
	var textColor = '#ede4e4';//状态文本的颜色
	var textStr = '未开始';//状态文本的显示
	switch (result) {//0失败，1进行中，2完成
		case 0:
			textColor = '#f01149';
			textStr = '失败';
			$("#progress_"+id).removeClass('progress-bar-success');
			$("#progress_"+id).addClass('progress-bar-danger');
			$("#progress_"+id).removeClass('active');
			break;
		case 1:
			$("#progress_"+id).addClass('active');
			progress = progressData;
			textColor = '#4cfb32';
			textStr = '进行中...';
			$("#progress_"+id).css('width',progress+"%");
			$("#progress_"+id).html(progress+"%");
			break;
		case 2:
			$("#progress_"+id).removeClass('active');
			progress = progressData;
			textColor = '#4cfb32';
			textStr = '完成';
			$("#progress_"+id).css('width',progress+"%");
			$("#progress_"+id).html(progress+"%");
		break;
		default:
			break;
	}
	$("#"+id+" .progressStatus").html(textStr);
	$("#"+id+" .progressStatus").css('color',textColor);
}

//当开始换装时将右侧所有输入框置为不可用状态，之后还原为可用状态
function changeDisable(disable){
	$("select.signSelect").prop("disabled", disable);
	$("#changeBtn").prop("disabled", disable);
}
//根据选中平台信息动态查询该平台相关的各软件版本信息
function seachVersion(){
	var id = $('#platformId').val();
	if(id==""||id==null){
		alert("请选择查询的平台名称");
	}else{
		$.ajax({
			url : "../../../SoftwareVersionChange/getSoftwareVersion",
			type : "post",
			data : {
				"id" : id,
			},
			dataType : "json",
			async:false,
			success : function(data) {
				if(data.flag==0){
					var content = data.content;
					showSoftwareVersions(content);
				}else{
					console.log(data.errorInfo);
				}
			},
			error : function() {
			}
		});
	}
}
function showSoftwareVersions(data){
	
}

//点击换装按钮，执行换装
function versionChangeFun(){
	var versionChanges = {id:lkjPlatFormId,softwares:JSON.stringify(changeObjs)};
	//发起换装请求
	$.ajax({
		url:'../../../SoftwareVersionChange/lkjSoftWareChange',
		type:'POST',
		traditional:true,
		contentType:"application/x-www-form-urlencoded; charset=utf-8",
		data:versionChanges,
		async:false,
		success:function(data){
			if(data.flag==0){
				initWC(JSON.stringify({id:lkjPlatFormId,type:'1',softwares:data.content}));
			}else{
				danger(data.errorInfo);
			}
		},
		error:function(){
			console.log('error');
		}
	});
}

function backFun(){
	history.back(-1);
}